package beans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.component.UIData;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;
import basicas.Badge;

public class BadgeBean {

	private Badge badge = new Badge();
	private List<Badge> badges = new ArrayList<Badge>();
	private UIData objDataTableBadge;
	private String desc = "";

	public String salvar() {
		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();

		try {
			session.merge(badge);
			t.commit();
			badge = new Badge();
		} catch (Exception e) {
			t.rollback();
			System.out.println(e);
		} finally {
			session.close();
		}
		return null;

	}

	public String excluir() {
		// PEGA O OBJETO DA LINHA SELECIONADA
		badge = (Badge) objDataTableBadge.getRowData();

		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();
		try {
			session.delete(badge);
			t.commit();
			badge = new Badge();
		} catch (Exception e) {
			t.rollback();
			System.out.println(e);
		} finally {
			session.close();
		}
		return null;

	}

	public String alterar() {
		badge = (Badge) objDataTableBadge.getRowData();
		return "alterarBadge";
	}

	public List<Badge> listarTodos() {
		Session session = HibernateUtil.getSession();
		Query q = session.createQuery("from Badge");
		List<Badge> badges = q.list();
		session.close();
		return badges;
	}

	public List<Badge> listarBadge(String nome) {
		Session session = HibernateUtil.getSession();
		Query q = session.createQuery("from Badge b where b.nome like :nome");
		q.setParameter("nome", "%" + nome + "%");
		List<Badge> badges = q.list();
		session.close();
		return badges;
	}

	public String pesquisaBadge() {
		if (desc.equals("")) {
			badges = listarTodos();
		} else {
			badges = listarBadge(desc);
		}
		return null;
	}

	public Badge getBadge() {
		return badge;
	}

	public void setBadge(Badge badge) {
		this.badge = badge;
	}

	public List<Badge> getBadges() {
		if (desc.equals("")) {
			badges = listarTodos();
			return badges;
		} else {
			return badges;
		}
	}

	public void setBadges(List<Badge> badges) {
		this.badges = badges;
	}

	public UIData getObjDataTableBadge() {
		return objDataTableBadge;
	}

	public void setObjDataTableBadge(UIData objDataTableBadge) {
		this.objDataTableBadge = objDataTableBadge;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

}
